const express = require("express");
const multer = require("multer")
const { db, genid } = require("../db/DbUtils.js")
const { cfile } = require("../utils/MachiningFiles.js")
const { jwts } = require("../utils/JsonWebtoken.js")
const { checks } = require("../utils/Validator.js")

const router = express.Router();


// 文件储存引擎 设置文件储存位置
const storage = multer.diskStorage({
    // 保存路径
    destination: function (req, file, cb) {
        // token验证
        let token = req.headers.authorization
        token = token.substring(0,token.indexOf(","))  //???????????????????? 为啥又有个点儿啊？
        let user_id = jwts.verifyToken(token)

        if (user_id === null || user_id === undefined) {
            cb(new Error('token不合法'), false)
            return ;
        }
        let file_ext = file.originalname.substring(file.originalname.lastIndexOf(".") + 1);

        // 验证文件 将文件放入对应用户的文件夹下
        if (file_ext !== "jpg" && file_ext !== "png") {
            cb(new Error('文件类型不合法'), false)
            return ;
        }
        if (user_id === undefined && user_id === null) {
            cb(new Error("表单参数不合法"), false)
            return ;
        } else {
            if (file.mimetype === 'application/octet-stream') {
                cb(null, './public/upload/' + user_id + "/tmp/")
            } else {
                cb(null, './public/upload/' + user_id)
            }
        }
    },
    // 文件名
    filename: function (req, file, cb) {
        let { file_hash, file_index } = req.body;
        let file_ext = file.originalname.substring(file.originalname.lastIndexOf(".") + 1);

        function isNumber(val){
            var regPos = /^[0-9]+.?[0-9]*/; //判断是否是数字。
            if(regPos.test(val) ){
                return true;
            }else{
                return false;
            }
        }

        if (isNumber(file_index) !== true) {
            cb(new Error("表单参数不合法"), false)
            return ;
        }
        if (file.mimetype === 'application/octet-stream') {
            cb(null, file_index + "-" + file_hash + "." + file_ext)
        } else {
            cb(null, genid.NextId() + "." + file_ext)
        }
    }
});
// 文件储存中间件
const upload = multer({ storage: storage })


// 文件上传接口
router.post("/", upload.any(), async (req, res) => {

    // token验证
    let token = req.headers.authorization
    token = token.substring(0,token.indexOf(","))
    let user_id = jwts.verifyToken(token)
    if (!user_id) {
        res.send({
            code: 500,
            msg: "bad"
        })
        return ;
    }

    // 获取响应的文件
    if (!req.files) {
        res.send({
            "errno": 500,
            "message": "文件不存在 上传失败",
        });  // res后仍会执行 但不会执行第二个res
        return ;
    }

    if (req.files[0].filename.length < 20) {
        res.send({
            "errno": 0,
            "file_path": user_id + "/" + req.files[0].filename,
            "msg": "Cool1"
        });
        return ;
    }

    res.send({
        "msg": "OK"
    });
    return ;
})


router.post("/merge", checks.uploadFiles() ,async (req, res) => {

    // token验证
    let token = req.headers.authorization
    token = token.substring(0,token.indexOf(","))
    let user_id = jwts.verifyToken(token)
    if (!user_id) {
        return ;
    }

    let { chunk_num, file_hash } = req.body;
    let chunk_path = process.cwd() + "\\public\\upload\\" + user_id + "\\tmp";
    let new_fileHash = genid.NextId()

    function promise() {

        return new Promise((resolve, resject) => {
            cfile.mergeFiles(chunk_path, file_hash, new_fileHash, chunk_num, (err, rel_ext) => {
                if (err !== undefined && err !== null) {
                    console.log(err);
                    res.send({
                        msg: "bad"
                    })
                    return;
                } else {
                    res.send({
                        // file_path: new_fileHash + rel_ext,
                        "file_path": user_id + "/" + new_fileHash + rel_ext,
                        "msg": "Cool2"
                    })
                    resolve()
                }
            })
        })
    }

    promise()
})

module.exports = router;
